import './Map.scss'
import { useRequest, useEventEmitter } from 'ahooks'
import { Http } from '../../../../Common/Api'
import { useEffect, useState, useRef } from 'react'
import { useLatest } from '@ant-design/pro-components'
import { initializationPlaneMap } from '../Common/PlaneMap'
import { project } from '../../../../Common/Data'
import { commonImageUrl } from '../../../../Common/Configure/CommonParameter'

import { Initialization, InitializationData } from '../../../../Common/Mars3d/Initialization'

import { WebTemplateUrl } from '../Template/configuration'

const { mars3d } = window
const { hostname } = window.location
const { imageUrl } = project[hostname]
const ProjectColor = ['#1149ff', '#83c306', '#00c044']

const JSZX = ['jszx.ljkjkf.com']

const ImageType = {
    1: 'command002.png',
    2: 'command001.png',
    3: 'command002.png',
}

// 建设中心地图
export const MapA01 = ({ sceneId, MapOptions, MapSetUp, type }) => {
    const Mars3dBox = useRef()
    const [Map, setMap] = useState()
    const [Gra, setGra] = useState()

    const [ActiveValue, setActiveValue] = useState()
    const ActiveLater = useLatest(ActiveValue)

    const { runAsync: getScenesDetailsUuid } = useRequest(Http, { manual: true })
    const { runAsync: getProjectList } = useRequest(Http, {
        manual: true,
        onSuccess: ({ list }) => {
            getScenesDetailsUuid({ url: 'getScenesDetailsUuid', path: [sceneId] }).then(({ elements }) => {
                const [polyline, point] = elements
                const polylineElement = polyline.elementDetails
                const pointElement = point.elementDetails
                list.forEach(item => {
                    if (!item.customData) return
                    const add = JSON.parse(item.customData)
                    const attr = add.find(v => v.one === 'attr')?.two //0
                    const point = add.find(v => v.one === 'point')?.two //2
                    const polyline = add.find(v => v.one === 'polyline')?.two //1
                    if (!attr || !point || !polyline) return

                    item.attr = attr
                    item.center = pointElement.find(v => v.elementDetailUuid === point).center
                    polyline.split(',').forEach(key => {
                        const line = new mars3d.graphic.PolylineEntity({
                            positions: polylineElement.find(v => v.elementDetailUuid === key).position,
                            name: item.fullName + '#polyline',
                            attr,
                            id: key,
                            style: {
                                width: 10,
                                color: ProjectColor[Number(item.remark) - 1],
                                depthFail: false,
                                outline: true,
                                outlineColor: '#06088e',
                                outlineWidth: 3,
                            },
                        })
                        Gra.addGraphic(line)
                    })

                    const text = new mars3d.graphic.LabelEntity({
                        position: pointElement.find(v => v.elementDetailUuid === point).position,
                        name: item.fullName + '#point',
                        attr,
                        id: point,
                        show: true,
                        style: {
                            text: item.fullName,
                            font_size: 40,
                            font_family: '微软雅黑',
                            font_weight: 'bold',
                            color: '#FFFFFF',
                            outline: true,
                            outlineColor: '#06088e',
                            outlineWidth: 2,
                            visibleDepth: false,
                            scaleByDistance: true,
                        },
                    })
                    const active = new mars3d.graphic.DivGraphic({
                        position: pointElement.find(v => v.elementDetailUuid === point).position,
                        id: point + '#active',
                        name: item.fullName,
                        attr,
                        show: false,
                        style: {
                            html: `<div class="ActiveBox">
                                        <div class="title">
                                            <img src='${imageUrl}${
                                item.projectStatus === 0 ? 'HomeIcon002' : 'HomeIcon001'
                            }.png'/>
                                            <div>
                                                <div>${item.fullName}</div>
                                                <div>
                                                    <div>总投资额：${item.totalInvestAmount}亿</div>
                                                    <div>累计投资：${item.accruingAmount}亿</div>
                                                </div>
                                            </div>
                                        </div>
                                        <img src='${imageUrl}MapSelect.png' />
                                        </div>`,
                        },
                    })
                    Gra.addGraphic(text)
                    Gra.addGraphic(active)
                })

                const ClearStyle = graphic => {
                    const state = Number(list.find(v => v.attr === ActiveLater.current).remark) - 1
                    const OptionsList = Gra.getGraphicsByAttr(ActiveLater.current, 'attr')
                    const polyline = OptionsList.filter(v => v.type === 'polyline')
                    const labelData = OptionsList.filter(v => v.type === 'label')
                    const divData = OptionsList.filter(v => v.type === 'div')
                    labelData[0].show = true
                    divData[0].show = false
                    polyline.forEach(item => {
                        item.setOptions({ style: { color: ProjectColor[state], outlineColor: '#06088e' } })
                    })
                    NewStyle(graphic)
                }
                const NewStyle = graphic => {
                    const OptionsList = Gra.getGraphicsByAttr(graphic.attr, 'attr')
                    const polyline = OptionsList.filter(v => v.type === 'polyline')
                    const labelData = OptionsList.filter(v => v.type === 'label')
                    const divData = OptionsList.filter(v => v.type === 'div')
                    labelData[0].show = false
                    divData[0].show = true
                    polyline.forEach(item => {
                        item.setOptions({ style: { color: '#FFDA59', outlineColor: '#ff4901' } })
                    })
                    setActiveValue(graphic.attr)
                }
                Gra.on('click', e => {
                    const { graphic } = e
                    if (type === 'Click') {
                        if (!ActiveLater.current) NewStyle(graphic)
                        else if (ActiveLater.current && ActiveLater.current !== graphic.attr) ClearStyle(graphic)
                    }
                })
            })
        },
    })

    const InitializationEvent = useEventEmitter()
    InitializationEvent.useSubscription(({ map, gra, uuid }) => {
        getScenesDetailsUuid({ url: `getScenesDetailsUuid`, path: [uuid] }).then(res => {
            InitializationData(map, gra, res)
            setGra(gra)
            setMap(map)
        })
    })

    const { run: getScenes } = useRequest(Http, {
        manual: true,
        onSuccess: res => Initialization(res, Mars3dBox, InitializationEvent),
    })

    const { runAsync: getAllPositions } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            if (Map.getLayerById('Helmet')) Map.getLayerById('Helmet').clear()
            else Map.addLayer(new mars3d.layer.GraphicLayer({ id: 'Helmet' }))
            Object.keys(res).forEach(key => {
                if (res[key]?.lon && res[key]?.lat) {
                    const { lon, lat, helmetType } = res[key]
                    const active = new mars3d.graphic.DivGraphic({
                        position: [lon, lat, 0],
                        style: {
                            clampToGround: true,
                            html: `<div class="HelmetPosition">
                                    <div>${key}</div>
                                    <img src='${commonImageUrl}${ImageType[helmetType]}' />
                                </div>
                                `,
                        },
                    })
                    Map.getLayerById('Helmet').addGraphic(active)
                }
            })
        },
    })

    useEffect(() => {
        if (JSZX.includes(hostname)) {
            const { map, gra } = initializationPlaneMap(Mars3dBox, MapOptions, MapSetUp)
            setMap(map)
            setGra(gra)
        } else {
            getScenes({ url: `getScenesID`, path: [sceneId] })
        }
    }, [MapOptions, MapSetUp, getScenes, sceneId])

    useEffect(() => {
        if (Map && Gra) {
            getProjectList({ url: 'getProjectList' })
            if (type === 'Helmet') getAllPositions({ url: 'getHelmetAllPositions' })
        }
    }, [Gra, Map, getAllPositions, getProjectList, type])

    return (
        <>
            <div className="MapA01" ref={Mars3dBox} />
            {!JSZX.includes(hostname) && <img className="Mask" src={WebTemplateUrl + 'Mask.png'} alt="" />}
        </>
    )
}
